package com.hashcoding.eyes.module.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.hashcoding.eyes.EyesApplication;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

public class Util {

    /**
     * 显示软键盘.
     *
     * @param view the view
     */
    public static void showSoftInput(View view) {
        InputMethodManager imm = (InputMethodManager) EyesApplication.gContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 隐藏软键盘.
     *
     * @param view the view
     */
    public static void hideSoftInput(View view) {
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) EyesApplication.gContext
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 显示软键盘.
     *
     * @param activity
     */
    public static void showSoftInput(Activity activity) {
        // 判断隐藏软键盘是否弹出
        if (activity.getWindow().getAttributes().softInputMode != WindowManager
                .LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
            // 隐藏软键盘
            activity.getWindow().setSoftInputMode(WindowManager.LayoutParams
                    .SOFT_INPUT_STATE_VISIBLE);
        }
    }

    /**
     * 隐藏软键盘.
     *
     * @param activity
     */
    public static void hideSoftInput(Activity activity) {
        // 判断隐藏软键盘是否弹出
        if (activity.getWindow().getAttributes().softInputMode == WindowManager
                .LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
            // 隐藏软键盘
            activity.getWindow().setSoftInputMode(WindowManager.LayoutParams
                    .SOFT_INPUT_STATE_HIDDEN);
        }
    }

    public static String encodeUrl(String url, Map<String, String> params) {
        String urlStr = url;
        if (!urlStr.contains("?")) {
            urlStr += '?';
        }
        urlStr += encodeParams(params);
        return urlStr;
    }

    public static String encodeParams(Map<String, String> params) {
        StringBuilder encodedParams = new StringBuilder();
        String paramsEncoding = "UTF-8";
        try {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            int size = entrySet.size();
            int index = 0;
            for (Map.Entry<String, String> entry : entrySet) {
                encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
                encodedParams.append('=');
                encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
                if (++index < size) {
                    encodedParams.append('&');
                }
            }
            return encodedParams.toString();
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
        }
    }

    /**
     * 加密签名
     *
     * @param strSrc  要加密的字符串
     * @param encName 加密类型
     * @return 签名值
     */
    public static String encrypt(String strSrc, String encName) {
        String sign = "";
        try {
            MessageDigest md = MessageDigest.getInstance(encName);
            sign = byte2hex(md.digest(strSrc.getBytes("utf-8")));
        } catch (Exception e) {
            // ignore
        }

        return sign;
    }

    /**
     * 二行制转字符串
     *
     * @param bytes
     */
    private static String byte2hex(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        String temp;
        for (byte b : bytes) {
            temp = (Integer.toHexString(b & 0XFF));
            if (temp.length() == 1) builder.append("0").append(temp);
            else builder.append(temp);
        }
        return builder.toString().toLowerCase(Locale.CHINA);
    }

    /**
     * 对参数进行排序并组合MD5签名
     *
     * @param map 参数map
     * @param key 特殊字符串
     * @return
     */
    public static String signature(Map<String, String> map, String key) {
        if (null == map || map.isEmpty()) return "";

        List<Map.Entry<String, String>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> lhs, Map.Entry<String, String> rhs) {
                return lhs.getKey().compareTo(rhs.getKey());
            }
        });

        final StringBuilder builder = new StringBuilder();
        int size = list.size();
        HashMap.Entry<String, String> entryFirst = list.get(0);
        builder.append(encode(entryFirst.getKey()));
        builder.append("=");
        builder.append(encode(entryFirst.getValue()));
        for (int i = 1; i < size; i++) {
            HashMap.Entry<String, String> entry = list.get(i);
            builder.append("&");
            builder.append(encode(entry.getKey()));
            builder.append("=");
            builder.append(encode(entry.getValue()));
        }
        builder.append(key);

        String source = builder.toString();
        String sign = Util.encrypt(builder.toString(), "MD5");
        LogUtil.d("Request", "Params signature:\nSource: " + source + "\n" + "MD5: " + sign);
        return sign;
    }

    // 11位手机号
    private static Pattern PHONE_PATTERN = Pattern.compile("^1\\d{10}$");

    // 4位验证码
    private static Pattern CODE_PATTERN = Pattern.compile("^\\d{4}$");

    public static boolean checkCode(String checkString) {
        return !TextUtils.isEmpty(checkString) && CODE_PATTERN.matcher(checkString).find();
    }

    public static boolean checkPhone(String checkString) {
        return !TextUtils.isEmpty(checkString) && PHONE_PATTERN.matcher(checkString).find();
    }

    public static String encode(String str) {
        try {
            if (!TextUtils.isEmpty(str)) {
                return URLEncoder.encode(str, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }

    public static String decode(String str) {
        try {
            if (!TextUtils.isEmpty(str)) {
                return URLDecoder.decode(str, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }

    public static String decodeUnicode(String str) {
        if (TextUtils.isEmpty(str)) {
            return "";
        }

        StringBuilder builder = new StringBuilder();
        int length = str.length();
        for (int i = 0; i < length; i++) {
            if (str.charAt(i) == '\\') {
                if ((i < length - 5) && ((str.charAt(i + 1) == 'u')
                        || (str.charAt(i + 1) == 'U'))) {
                    try {
                        builder.append((char) Integer.parseInt(str.substring(i + 2, i + 6), 16));
                        i += 5;
                    } catch (NumberFormatException localNumberFormatException) {
                        builder.append(str.charAt(i));
                    }
                } else {
                    builder.append(str.charAt(i));
                }
            } else {
                builder.append(str.charAt(i));
            }
        }
        return builder.toString();
    }

    public static final int REQUEST_IMAGE_ALBUM_OPEN = 1001;

    public static final boolean gotoAlbumView(Activity act, int requestid, boolean bOnlyImage) {
        Uri uri = null;
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else {
            uri = android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;
        }
        if (bOnlyImage) {
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            act.startActivityForResult(i, requestid);
            return true;
        }

        boolean flag = false;
        if (uri != null) {
            try {
                Intent intentImage = new Intent(Intent.ACTION_GET_CONTENT, uri);
                intentImage.addCategory(Intent.CATEGORY_OPENABLE);
                intentImage.setType("image/*");
                String title = "添加图片";

                Intent chooser = Intent.createChooser(intentImage, title);
                if (chooser != null) {
                    if (requestid > 0)
                        act.startActivityForResult(chooser, requestid);
                    else
                        act.startActivity(chooser);
                    return true;
                } else {
                    flag = true;
                }
            } catch (RuntimeException e) {
                flag = true;
            }
        }
        return flag;
    }
}